package models

import (
	"fmt"
	"time"
	"github.com/jinzhu/gorm"
)

type UserDevice struct {
	ID          int    `json:"-"`
	UserId 		int `json:"user_id"`
	UserAccount string `json:"user_account"`
	DeviceID    string `json:"device_id"`
	System      string `json:"system"`
	Version      string `json:"version"`
	DeviceName  string `json:"device_name"`
	FirstLoginTime int64 `json:"-"`
	LastLoginTime  int64 `json:"-"`
}

func (tag *UserDevice) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("FirstLoginTime", time.Now().Unix())
	return nil
}
func (tag *UserDevice) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("LastLoginTime", time.Now().Unix())
	return nil
}
func AddUserDevice(data map[string]interface{}) bool {
	var res = db.Create(&UserDevice{
		UserId: data["user_id"].(int),
		UserAccount: data["user_account"].(string),
		DeviceID:   data["device_id"].(string),
		System:      data["system"].(string),
		DeviceName:  data["device_name"].(string),
	})
	if res.Error != nil{
		fmt.Println("Error：",res.Error)
		return false
	}
	return true
}

func EditUserDevice(userid int,DeviceName string, maps UserDevice) bool {
	var dbUser UserDevice
	db.Where("user_id = ? and device_id = ?", userid,DeviceName).First(&dbUser)
	if dbUser.ID > 0 {
		// 条件匹配,更新
		db.Model(&UserDevice{}).Where("user_id = ? and device_id = ?", userid,DeviceName).Update(maps)
	} else {
		// 条件不匹配,插入
		db.Create(&maps)
	}
	return true
}

func GetDeviceLists(PageNum int, PageSize int, userid int) (device []UserDevice) {
	db.Where("user_id = ?", userid).Order("id desc").Offset(PageNum).Limit(PageSize).Find(&device)
	return
}
